import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Picker, Text} from "@tarojs/components";
import {REPORT_ORDER_NUM_DATA, RESOURCE_URL} from '../../../constants/api';
import GzhAuth from '../../../components/gzh-auth/gzh-auth';
import {http} from '../../../utils/http';
import {h5Wx} from '../../../utils/h5.service';
import {GetRequest, vcmonitor} from "../../../utils/tools";
import "./promotionOrder.scss";

export default class Member extends Component {
  state: {
    tabList: any
    curTabIndex: any
    listInfo: any
    // Tab 激活状态
    active: number
    // 日报
    day_date: string
    // 月报
    month_date: string
    // 自定义 起始时间
    show: boolean
    start_date: string
    end_date: string
    // 右侧显示的文本
    date_right: string
  } = {
    tabList: [{name: '全部'}, {name: '已付款'}, {name: '已完成'}, {name: '待使用'}, {name: '已付款'}],
    curTabIndex: 0,
    listInfo: [],
    // Tab 激活状态
    // 1:日报 2:月报 3:自定义
    active: 1,
    // 日报
    day_date: "",
    // 月报
    month_date: "",
    // 自定义 起始时间
    show: false,
    start_date: "起始时间",
    end_date: "终止时间",
    // 右侧显示的文本
    date_right: "2021/10/01",
  };

  async componentDidShow() {
    vcmonitor(this)
    if (process.env.TARO_ENV === "h5") {
      await h5Wx.getConfig();
    }
    // 获取当前时间戳 转换为 2021/10/01 格式
    const date = new Date();
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    month = +month;
    day = +day;
    month = month >= 10 ? month : "0" + month;
    day = day >= 10 ? day : "0" + day;
    let temp = "";
    temp = year + "/" + month + "/" + day;
    this.setState({date_right: temp});
    // 时间格式转换成-
    temp = this.timeFormatConversion(temp);
    await this.setStateSync({day_date: temp});
    // 设置默认 起始时间
    await this.setState({start_date: temp, end_date: temp});

    // 设置默认 年月
    await this.setState({month_date: temp.slice(0, 7)});
    const {search_date_start = '', search_date_end = '', search_month = '', active = 0} = Taro.getCurrentInstance().router.params
    if (active == 1) {
      await this.setStateSync({day_date: search_date_start, date_right: search_date_start})
    } else if (active == 2) {
      await this.setStateSync({month_date: search_month, date_right: search_month})
    } else if (active == 3) {
      await this.setStateSync({show: true, start_date: search_date_start, end_date: search_date_end})
    }
    await this.setStateSync({active: +active})
    // 获取 数据总览
    this.getDataOverView();
  }
  page = 1
  info
  // 获取 数据总览
  async getDataOverView() {
    Taro.showLoading({ title: '加载中...' })
    const {curTabIndex, start_date, day_date, month_date, end_date, active} = this.state
    const tempObj = {
      page: this.page,
      length: 10,
      search_type: curTabIndex
    };
    if (active == 1) {
      tempObj.search_date_start = day_date;
      tempObj.search_date_end = day_date;
    } else if (active == 2) {
      tempObj.search_month = month_date;
    } else if (active == 3) {
      tempObj.search_date_start = start_date;
      tempObj.search_date_end = end_date;
    }
    const ret = await http.HGet(REPORT_ORDER_NUM_DATA, tempObj);
    let list = false
    if(ret && ret.data && ret.data.list){
      list = ret.data.list
    }
    if (list && list.length > 0) {
      if (this.page === 1) {
        this.setState({listInfo: list})
      } else if (this.page > 1) {
        const oldData = this.state.listInfo;
        this.setState({listInfo: [...oldData, ...list]})
      }
    } else {
      if (this.page === 1) {
        this.setState({listInfo: []})
      }
    }
    Taro.hideLoading()
  }
  async onReachBottom() {
    this.page++
    await this.getDataOverView()
  }
  // 日报
  async bindDayDateChange(e) {
    await this.setStateSync({active: 1});
    await this.setStateSync({day_date: e.detail.value});
    this.setState({show: false});
    this.setState({date_right: e.detail.value.split("-").join("/")});

    // 获取 数据总览
    this.getDataOverView();
  }

  // 月报
  async bindMonthDateChange(e) {

    await this.setStateSync({active: 2});
    await this.setStateSync({month_date: e.detail.value});
    this.setState({show: false});
    this.setState({date_right: e.detail.value.split("-").join("/")});

    // 获取 数据总览
    this.getDataOverView();
  }

  // 起
  async bindStartDateChange(e) {

    await this.setStateSync({start_date: e.detail.value});
    this.setState({date_right: "全部"});
    // 获取 数据总览
    this.getDataOverView();
  }

  // 止
  async bindEndDateChange(e) {
    this.page = 1
    await this.setStateSync({end_date: e.detail.value});
    this.setState({date_right: "全部"});
    // 获取 数据总览
    this.getDataOverView();
  }

  // 点击 切换 Tabs active
  async activeTabs(num) {
    this.page = 1
    await this.setStateSync({active: num})
    if (num == 1) {
      let temp = this.state.day_date
      if (temp.indexOf('-')) {
        temp = this.timeFormatConversionElse(temp)
      }
      this.setState({date_right: temp})
    }
    if (num == 2) {
      let temp = this.state.month_date
      if (temp.indexOf('-')) {
        temp = this.timeFormatConversionElse(temp)
      }
      this.setState({date_right: temp})
    }
    // 显示 自定义 日期区间选择器
    if (num == 3 && this.state.show == false) {
      this.setState({show: true});
    } else {
      this.setState({show: false});
    }
    // 获取 数据总览
    this.getDataOverView();
  }

  // 时间格式转换  /转-
  timeFormatConversion(str) {
    return str.split("/").join("-");
  }

  // 时间格式转换  -转/
  timeFormatConversionElse(str) {
    return str.split("-").join("/");
  }

  // setState 异步转同步
  setStateSync(state) {
    return new Promise(resolve => {
      this.setState(state, resolve);
    });
  }
  async tabChange(curTabIndex){
    if(this.state.curTabIndex !== curTabIndex){
      await this.setStateSync({ curTabIndex, page: 1 })
      // 获取 数据总览
      this.getDataOverView();
    }
  }
  render() {
    const {
      listInfo,
      active,
      show,
      start_date,
      end_date,
      tabList,
      curTabIndex,
      date_right,
    } = this.state;

    return (
      <View className='report'>
        <GzhAuth />
        <View className='report-wrapper'>
          <View className='select-time'>
            <View className='left flex-row'>
              <View
                className={`mar-right ${active === 1 ? "tab-active" : "tab-no-active"
                }`}
                onClick={this.activeTabs.bind(this, 1)}
              >
                <View>日报</View>
              </View>
              <View
                className={`mar-right ${active === 2 ? "tab-active" : "tab-no-active"
                }`}
                onClick={this.activeTabs.bind(this, 2)}
              >
                <View>月报</View>
              </View>
              <View
                className={`${active === 3 ? "tab-active" : "tab-no-active"
                }`}
                onClick={this.activeTabs.bind(this, 3)}
              >
                <View>自定义</View>
              </View>
            </View>
            {/* 右侧的 picker 组 */}
            <View className='right'>
              {/* 年 月 日 */}
              {active == 1 ? (
                <View className='section'>
                  <Picker
                    mode='date'
                    value='{day_date}'
                    start='1970-01-01'
                    end='2050-01-01'
                    onChange={this.bindDayDateChange.bind(this)}
                  >
                    {date_right}
                  </Picker>
                </View>
              ) : (
                <View />
              )}
              {/* 年 月 */}
              {active == 2 ? (
                <View className='section'>

                  <Picker
                    mode='date'
                    value='{month_date}'
                    start='1970-01-01'
                    end='2050-01-01'
                    fields='month'
                    onChange={this.bindMonthDateChange.bind(this)}
                  >
                    {date_right}
                  </Picker>
                </View>
              ) : (
                <View />
              )}
              {/* 自定义 不显示右侧 picker  */}
              {active == 3 ? (
                <View />
              ) : (
                <Image
                  className='arrow-right-image-rotate'
                  src='https://resource.ivcheng.com/resources/images/arrow-right.png'
                />
              )}
            </View>
          </View>
          {/* 自定义 日期区间选择器 */}
          {!show ? (
            <View />
          ) : (
            <View className='select-time-start-end'>
              <View className='item'>
                <Picker
                  mode='date'
                  value='{start_date}'
                  start='1970-01-01'
                  end='2050-01-01'
                  onChange={this.bindStartDateChange.bind(this)}
                >
                  <View className='pickerr'>{start_date}</View>
                </Picker>
              </View>
              <View style='color: #666;'>—</View>
              <View className='item'>
                <Picker
                  mode='date'
                  value='{end_date}'
                  start='1970-01-01'
                  end='2050-01-01'
                  onChange={this.bindEndDateChange.bind(this)}
                >
                  <View className='pickerr'>{end_date}</View>
                </Picker>
              </View>
            </View>
          )}
          <View className='tab-wrapper'>
            {tabList.map((item, index) => <View onClick={this.tabChange.bind(this, index)} key={index} className={`tab-items ${curTabIndex === index && 'tab-active'}`}>{ item.name }</View>)}
          </View>
        </View>
        {listInfo && listInfo.length > 0 && <View className='order-list-promotionOrder'>
          {listInfo.map((item, index) => <View key={index} className='order-list-items-promotionOrder'>
              <View className='order-list-item'>
                <View className='order-list-item-left'>订单号：</View>
                <View className='order-list-item-right'>{ item.order_num } <View className='order-status'>{item.status_name}</View></View>
              </View>
            <View className='order-list-item'>
              <View className='order-list-item-left'>商品名称：</View>
              <View className='order-list-item-right-name'>{ item.product_name }</View>
            </View>
            <View className='order-list-item'>
              <View className='order-list-item-left'>付款时间：</View>
              <View className='order-list-item-right'>{ item.offpay_date }</View>
            </View>
            { item.status !==4 &&<View className='order-list-item'>
              <View className='order-list-item-left'>预估收益：</View>
              <View className='order-list-item-right order-list-item-right-num font-family-price'>￥{ item.total_amount }</View>
            </View>}
            { item.status ===4 && <View className='order-list-item'>
              <View className='order-list-item-left'>失效收益：</View>
              <View className='order-list-item-right order-list-item-right-num font-family-price'>￥{ item.total_amount }</View>
            </View>}
            </View>
          )}
        </View>}
        {listInfo.length <= 0 && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/upload/images/20211112/1636708674979_153.png`} mode='widthFix' />
          <View className='text'>暂无数据</View>
        </View>}
        <View style='height: 30px;'></View>
      </View>
    );
  }
}
